import { addPlatFormModule, deleteModule, editModule, selectAllPlatFormModule } from '@/api/conf'
import CCard from '@/components/card'

import deepClone from '@/libs/deepClone'
import { FormInstance } from 'ant-design-vue'

interface Conf_modules_state {
  arrDataSource: User.InterfaceModule[]
  treeDataSource: User.InterfaceModule[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: 'addModule' | 'editModule' | 'deleteModule' | null
    /**弹窗 标题*/
    title: string
    /** 弹窗 修改 数据源 */
    edit_source: User.EditInterfaceModuleDataSource
    add_source: User.AddInterfaceModuleDataSource
    delete_source: { moduleId: ModuleId | null }
  }
}
export const conf_modules_state = reactive<Conf_modules_state>({
  arrDataSource: [],
  treeDataSource: [],
  modal: {
    visible: false,
    type: null,
    title: '',
    edit_source: {
      moduleDesc: '',
      moduleIcon: '',
      moduleId: 0,
      moduleName: '',
      moduleSort: '',
      moduleUrl: '',
      parentNode: ''
    },
    add_source: {
      moduleDesc: '',
      moduleIcon: '',
      moduleName: '',
      moduleSort: '',
      moduleUrl: '',
      parentNode: ''
    },
    delete_source: { moduleId: null }
  }
})

//? 接口区域 -----------------------------------
export const getTreeDatas = async () => {
  let res = await selectAllPlatFormModule().catch(err => {})
  if (res) {
    let { treeDataSource, arrDataSource } = toRefs(conf_modules_state)
    arrDataSource.value = res.data
    treeDataSource.value = arrToTree(res.data)
    console.log(treeDataSource.value)
  }
}

//? 复用组件 -----------------------------------

//? 页面组件 事件 -----------------------------------
/**将数组组合成树状结构数据 */
function arrToTree(data: User.InterfaceModule[]) {
  let arr = deepClone(data) as User.InterfaceModule[]
  arr.forEach(item => {
    let children = arr.filter(v => item.moduleId?.toString() === v.parentNode)
    item.moduleList = children.length > 0 ? (item.moduleList = children) : []
  })
  return arr.filter(item => item.parentNode === '0')
}

/**树状图右击下拉框点击事件 */
const onContextMenuClick = (treeKey: ModuleId, menuKey: 'edit' | 'addChildren' | 'delete') => {
  console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`)
  let { arrDataSource } = toRefs(conf_modules_state)
  let currentData = arrDataSource.value.filter(data => data.moduleId === treeKey)[0]
  let moduleId = currentData.moduleId?.toString()
  if (!moduleId) return
  let { visible, type, title, edit_source, add_source, delete_source } = toRefs(
    conf_modules_state.modal
  )
  switch (menuKey) {
    case 'edit':
      visible.value = true
      type.value = 'editModule'
      title.value = '修改模块: ' + currentData.moduleName
      Object.keys(edit_source.value).forEach(key => {
        // @ts-ignore
        edit_source.value[key] = currentData[key]
      })
      break
    case 'addChildren':
      visible.value = true
      type.value = 'addModule'
      title.value = '添加子模块: ' + currentData.moduleName
      add_source.value.parentNode = moduleId
      break
    case 'delete':
      visible.value = true
      type.value = 'deleteModule'
      title.value = '删除模块: ' + currentData.moduleName
      delete_source.value.moduleId = currentData.moduleId
      break
  }
}
//? 页面组件 -----------------------------------

export const MainViewContentNav = defineComponent({
  setup() {
    const handle_addModule_btn_click = () => {
      let { visible, type, title, add_source } = toRefs(conf_modules_state.modal)
      let { arrDataSource } = toRefs(conf_modules_state)
      visible.value = true
      type.value = 'addModule'
      title.value = '添加主模块'
      add_source.value.parentNode = '0'
    }
    return () => (
      <div class='h-mainViewNav bg-white border-b border-default flex justify-center items-center'>
        <a-button type='primary' onClick={handle_addModule_btn_click}>
          添加主模块
        </a-button>
      </div>
    )
  }
})

export const MainViewContent = defineComponent({
  setup() {
    return () => (
      <div class='h-mainViewcontentNoFooter py-2 '>
        <CCard title='' showTitle={false}>
          <MainViewContentTree></MainViewContentTree>
        </CCard>
      </div>
    )
  }
})

const MainViewContentTree = defineComponent({
  setup() {
    let { treeDataSource } = toRefs(conf_modules_state)
    let expandedKeys = ref<number[]>([])
    const expandedKeys_computed = computed(() =>
      treeDataSource.value.filter(item => item.parentNode === '0').map(item => item.moduleId)
    )
    watch(
      () => expandedKeys_computed.value,
      n => {
        expandedKeys.value = n
      }
    )
    onMounted(() => {
      getTreeDatas()
    })
    return () => (
      <a-tree
        v-model={[expandedKeys.value, 'expandedKeys']}
        tree-data={treeDataSource.value}
        fieldNames={{
          children: 'moduleList',
          title: 'moduleName',
          key: 'moduleId'
        }}
        show-line
      >
        {{
          title: (treeData: User.InterfaceModule) => {
            return (
              <a-dropdown trigger={['contextmenu']}>
                {{
                  default: () => (
                    <div class='overflow-hidden py-1'>
                      <span class={['rounded bg-primary_light text-primary mx-1 p-1']}>
                        {treeData.moduleSort + '. '}
                      </span>
                      <span class='rounded bg-primary text-white mx-1 p-1'>
                        {treeData.moduleName}
                      </span>
                      <span class='rounded bg-success text-white mx-1 p-1'>
                        {treeData.moduleUrl}
                      </span>
                      <span
                        class={[
                          'rounded bg-info text-white mx-1 p-1',
                          treeData.moduleDesc ? '' : 'hidden'
                        ]}
                      >
                        {treeData.moduleDesc}
                      </span>
                    </div>
                  ),
                  overlay: () => (
                    <a-menu
                      onClick={({ key: menuKey }: KeyboardEvent) =>
                        onContextMenuClick(
                          treeData.moduleId,
                          menuKey as 'edit' | 'addChildren' | 'delete'
                        )
                      }
                    >
                      <a-menu-item key='edit'>修改</a-menu-item>
                      <a-menu-item key='addChildren'>添加子模块</a-menu-item>
                      <a-menu-item key='delete'>删除</a-menu-item>
                    </a-menu>
                  )
                }}
              </a-dropdown>
            )
          }
        }}
      </a-tree>
    )
  }
})

/**弹窗 表单 添加权限用 */
const AddFormOfModal = defineComponent({
  name: 'AddFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let formRef = ref<FormInstance>()
    let { add_source } = toRefs(conf_modules_state.modal)
    let onLoading = ref(false)
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      onLoading.value = true
      await addPlatFormModule(add_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', add_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      onLoading.value = false
      formRef.value?.resetFields()
      emit('finish')
    }

    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='addAuth'
        model={add_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='模块序号' name='moduleSort'>
          <a-input v-model={[add_source.value.moduleSort, 'value']} />
        </a-form-item>
        <a-form-item label='模块名称' name='moduleName'>
          <a-input v-model={[add_source.value.moduleName, 'value']} />
        </a-form-item>
        <a-form-item label='模块路径' name='moduleUrl'>
          <a-input v-model={[add_source.value.moduleUrl, 'value']} />
        </a-form-item>
        <a-form-item label='模块图标' name='moduleIcon'>
          <a-input v-model={[add_source.value.moduleIcon, 'value']} />
        </a-form-item>
        <a-form-item label='模块备注' name='moduleDesc'>
          <a-input v-model={[add_source.value.moduleDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button
            type='primary'
            class='float-right mx-4'
            html-type='submit'
            loading={onLoading.value}
          >
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/**弹窗 表单 修改权限用 */
const EditFormOfModal = defineComponent({
  name: 'EditFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let { edit_source } = toRefs(conf_modules_state.modal)
    let formRef = ref<FormInstance>()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      await editModule(edit_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', edit_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='editSysdictType'
        model={edit_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='模块序号' name='moduleSort'>
          <a-input v-model={[edit_source.value.moduleSort, 'value']} />
        </a-form-item>
        <a-form-item label='模块名称' name='moduleName'>
          <a-input v-model={[edit_source.value.moduleName, 'value']} />
        </a-form-item>
        <a-form-item label='模块路径' name='moduleUrl'>
          <a-input v-model={[edit_source.value.moduleUrl, 'value']} />
        </a-form-item>
        <a-form-item label='模块图标' name='moduleIcon'>
          <a-input v-model={[edit_source.value.moduleIcon, 'value']} />
        </a-form-item>
        <a-form-item label='模块备注' name='moduleDesc'>
          <a-input v-model={[edit_source.value.moduleDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type='primary' class='float-right mx-4' html-type='submit'>
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})
/**弹窗 表单 删除权限用 */
const DeleteFormOfModal = defineComponent({
  name: 'DeleteFormOfModal_modules',
  emits: ['finish'],
  setup(props, { emit }) {
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      let { delete_source } = toRefs(conf_modules_state.modal)

      await deleteModule({
        moduleId: delete_source.value.moduleId || 0
      }).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }

    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      emit('finish')
    }
    return () => (
      <div class='h-10'>
        <a-button type='primary' class='float-right mx-4' onClick={handle_form_finish}>
          确认
        </a-button>
        <a-button class='float-right mx-4' onClick={handle_form_cancel}>
          取消
        </a-button>
      </div>
    )
  }
})

/**弹窗 */
export const MainViewModel = defineComponent({
  setup() {
    let { visible, type, title } = toRefs(conf_modules_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = null
      title.value = ''
      getTreeDatas()
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addModule':
          dynamicCom = <AddFormOfModal onFinish={handle_form_finish}></AddFormOfModal>
          break
        case 'editModule':
          dynamicCom = <EditFormOfModal onFinish={handle_form_finish}></EditFormOfModal>
          break
        case 'deleteModule':
          dynamicCom = <DeleteFormOfModal onFinish={handle_form_finish}></DeleteFormOfModal>
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  }
})
